package edu.zut.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @WebServlet: 代替web.xml中的映射配置
 * name：servlet-name
 * value = url == urlPatterns
 */
@WebServlet(name = "ShowTimeServlet2", value = "/time/showTime2")
public class ShowTimeServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //记录显示上次访问当前应用的时间
        boolean flag = true;
        //获取请求中的所有cookie信息
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0){
            //遍历cookies
            for (Cookie cookie : cookies) {
                //获取当前cookie的name属性，判断是否包含lastTime
                if (cookie.getName().equals("lastTime")) {
                    //获取上次访问时间
                    String lastTime = cookie.getValue();
                    System.out.println("lastTime = " + lastTime);
                    String path = cookie.getPath();
                    System.out.println("path = " + path);
//                    cookie.setPath("/time");
                    //更新当前cookie的value值
                    lastTime = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss").format(new Date());
                    cookie.setValue(lastTime);
                    //设置cookie的有效期   持久化到本地
                    cookie.setMaxAge(60*60);
                    //重新把cookie返回给浏览器
                    response.addCookie(cookie);
                    flag = false;
                }
            }
        }
        if (cookies == null || cookies.length == 0 || flag) {
            String lastTime = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss").format(new Date());
            System.out.println("用户首次访问：" + lastTime);
            //cookie的创建
            Cookie cookie = new Cookie("lastTime", lastTime);
            //设置cookie的有效期   持久化到本地
            cookie.setMaxAge(60*60);
            //将cookie返回给浏览器
            response.addCookie(cookie);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
